<?php

namespace app\controllers;

use app\librarys\Inteface;
use app\librarys\BaseController;
use app\models\Activity;
use app\models\ApplyInstitution;
use app\models\Department;
use app\models\Goods;
use app\models\Information;
use app\models\Mall;
use app\models\Permission;
use app\models\User;
use yii\data\Pagination;
use app\models\Institution;
use app\models\Manager;
use app\models\InstitutionUpdateRecord;
use app\models\Role;
use Yii;

class InstitutionController extends BaseController
{
    public static $pageSize = 10;
    public static $demo_file = 'exportInstitutionDemo.xlsx';
    public static $download = 'download';

    /**
     * 机构列表主页
     * @return string
     */
    public function actionList()
    {
        //--获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构--------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //----------------------------------------------------------------------------
        $msg = "";

        $request = \Yii::$app->request;


        $start = $request->get("page");

        $status = $request->get("status");
        $filter = $request->get("filter");
        $filterP = $request->get("filterP");


        if ($start == '') {
            $start = 0;
        } else {
            $start = ($start - 1) * self::$pageSize;
        }
        if ($status == '') {
            $status = 99;
        }
        if ($filter == '') {
            $filter = 0;
        }
        if ($filterP == '') {
            $filterP = 0;
        }

        //父机构下拉列表相关数据
        $selectList = Institution::getInstitutionSelectList($institution, $filterP);

        $total_page = Institution::getInstitutionListTotal($status, $filter, $filterP, $institution);
        $record = Institution::getInstitutionList($start, self::$pageSize, $status, $filter, $filterP, $institution);

        $pagination = new Pagination([
            'defaultPageSize' => self::$pageSize,
            'totalCount' => $total_page,
        ]);

        return $this->render('list',
            ['institution' => $institution,
                'pagination' => $pagination,
                'record' => $record,
                'status' => $status,
                'filter' => $filter,
                'institutionList' => $selectList['institutionList'],
                'filterParent' => $selectList['selectedInstitution']]);
    }

    /**
     * 新增编辑旗下机构详情页面
     * @return string
     */
    public function actionInstitutionDetailHandler()
    {
        $record = [];
        $parent = [];
        $result = [];

        $request = \Yii::$app->request;
        $code = $request->post("institutionCode");
        $record['parentCode'] = $request->post("parentCode");

        if ($record['parentCode'] == '0') {
            $record['parentName'] = '无';
        } else {
            $parent = Institution::getInstitution($record['parentCode']);

            $record['parentName'] = $parent['name'];
        }

        if ($code == '0') {
            $record['code'] = null;
            //$record['parentCode'] = null;
            $record['name'] = null;
            $record['address'] = null;
            $record['isEnabled'] = 1;
            $record['isAutoOrder'] = 1;
            $record['isCashOrder'] = 1;
            $record['isAllowImportOrder'] = 1;
            $record['isCustomPrice']=0;
            $record['billModel'] = 1;
            $record['integralRate'] = 1;
            $record['integralUnit'] = '积分';
            //$record['createDatetime'] = $request->post("createDatetime");
            $record['remark'] = null;
            $record['siteName'] = null;
            $record['domain'] = null;
            $record['themePc'] = null;
            $record['themeM'] = null;
            //$record['account'] = null;
            //$record['token'] = null;
            $record['salesmanName'] = null;
            $record['salesmanPhone'] = null;

        } else {
            //根据机构code获取机构信息
            $result = Institution::getInstitution($code);
            $record['code'] = $result['code'];
            //$record['parentCode'] = null;
            $record['name'] = $result['name'];
            $record['address'] = $result['address'];
            $record['isEnabled'] = $result['is_enabled'];
            $record['isAutoOrder'] = $result['is_auto_order'];
            $record['isCashOrder'] = $result['is_cash_order'];
            $record['isAllowImportOrder'] = $result['is_allow_import_order'];
            $record['isCustomPrice']=$result['is_custom_price'];
            $record['billModel'] = $result['bill_model'];
            $record['integralRate'] = $result['integral_rate'];
            $record['integralUnit'] = $result['integral_unit'];
            //$record['createDatetime'] = $request->post("createDatetime");
            $record['remark'] = $result['remark'];
            $record['siteName'] = $result['site_name'];
            $record['domain'] = $result['domain'];
            $record['themePc'] = $result['theme_pc'];
            $record['themeM'] = $result['theme_m'];
            //$record['account'] = null;
            //$record['token'] = null;
            $record['salesmanName'] = $result['salesmanName'];
            $record['salesmanPhone'] = $result['salesmanPhone'];

            //        获取机构申请的信息
            $record['ins_info'] = ApplyInstitution::getInstitutionInfo($code);
        };

        $template_pc = Institution::getTemplate(1);
        $template_m = Institution::getTemplate(2);


        return $this->renderJson(['record' => $record, 'template_pc' => $template_pc, 'template_m' => $template_m], 0, $result);
    }

    /**
     * 机构基础信息
     * @return string
     */
    public function actionInstitutionInfo()
    {
        $record = [];
        $parent = [];
        $result = [];

        //--获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构--------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //----------------------------------------------------------------------------


        //根据机构code获取机构信息
        $result = Institution::getInstitution($institution);
        $record['code'] = $result['code'];
        $record['parentCode'] = $result['parent_code'];
        $record['name'] = $result['name'];
        $record['address'] = $result['address'];
        $record['isEnabled'] = $result['is_enabled'];
        $record['isAutoOrder'] = $result['is_auto_order'];
        $record['isCashOrder'] = $result['is_cash_order'];
        $record['isAllowImportOrder'] = $result['is_allow_import_order'];
        $record['isCustomPrice']=$result['is_custom_price'];
        $record['billModel'] = $result['bill_model'];
        $record['integralRate'] = $result['integral_rate'];
        $record['integralUnit'] = $result['integral_unit'];
        //$record['createDatetime'] = $request->post("createDatetime");
        $record['remark'] = $result['remark'];
        $record['siteName'] = $result['site_name'];
        $record['domain'] = $result['domain'];
        $record['themePc'] = $result['theme_pc'];
        $record['themeM'] = $result['theme_m'];
        //$record['account'] = $result['account'];
        //$record['token'] = $result['token'];
        $record['salesmanName'] = $result['salesmanName'];
        $record['salesmanPhone'] = $result['salesmanPhone'];

        if ($record['parentCode'] == '0') {
            $record['parentName'] = '无';
        } else {
            $parent = Institution::getInstitution($record['parentCode']);

            $record['parentName'] = $parent['name'];
        }


        $template_pc = Institution::getTemplate(1);
        $template_m = Institution::getTemplate(2);

        return $this->render('institution-info', ['record' => json_encode($record), 'template_pc' => json_encode($template_pc, true), 'template_m' => json_encode($template_m, true)]);
    }

    /**
     * 确认新增/修改机构
     * @return string
     */
    public function actionAddInstitutionHandler()
    {
        //获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构
        //$institution = 0;
        //$result = 0;

        $request = \Yii::$app->request;
        $record = [];
        $record['code'] = $request->post("institutionCode");
        $record['parentCode'] = $request->post("parentCode");
        $record['name'] = $request->post("name");
        $record['address'] = $request->post("address");
        $record['isEnabled'] = $request->post("isEnabled");
        $record['isAutoOrder'] = $request->post("isAutoOrder");
        $record['isCashOrder'] = $request->post("isCashOrder");
        $record['isAllowImportOrder'] = $request->post("isAllowImportOrder");
        $record['isCustomPrice']=$request->post("isCustomPrice");
        $record['billModel'] = $request->post("billModel");
        $record['integralRate'] = $request->post("integralRate");
        $record['integralUnit'] = $request->post("integralUnit");
        //$record['createDatetime'] = $request->get("createDatetime");
        $record['remark'] = $request->post("remark");
        $record['siteName'] = $request->post("siteName");
        $record['domain'] = $request->post("domain");
        $record['themePc'] = $request->post("themePc");
        $record['themeM'] = $request->post("themeM");
        //$record['account'] = $request->post("account");
        //$record['token'] = $request->post("token");
        $record['salesmanName'] = $request->post("salesmanName");
        $record['salesmanPhone'] = $request->post("salesmanPhone");


        $result = Institution::addInstitution($record);

        if ($result == null) {
            return $this->renderJson(null, 1, '创建机构失败');
        } else {
            return $this->renderJson($result, 0, 0);
        }
    }

    /**
     * 变更机构启用状态
     * @return string
     */
    public function actionModifyStatusHandler()
    {
        $request = \Yii::$app->request;
        $institutionId = $request->post("institutionCode");
        $result = Institution::setInstitutionStatus($institutionId);
        return $this->renderJson(0, 0, $result);
    }

    /**
     * 机构联系人
     * @return string
     */
    public function actionInstitutionContacterPartial()
    {
        //当前用户的机构-----------------------------------------------
//        $institutionCode = Manager::getCurrentManager()['institution_code'];
//        if ($institutionCode == '0') {
        $institutionCode = Yii::$app->request->post('institutionCode');
//        }
        //---------------------------------------------------------------

//        //下拉选择的机构
//        $institutionId = $request->get("institutionCode");
//        if ($institutionId == '') {
//            $institutionRecord = $institutionCode;
//        } else {
//            $institutionRecord = $institutionId;
//        }
//        $institutionList = Institution::getAllEnabledListWithHierarchy($institutionCode);
        /*//返回当前选中的机构
        if ($institutionId == '0' || $institutionId == '') {
            $institutionRecord['code'] = '0';
        } else {
            $institutionRecord = Institution::getInstitution($institutionId);
        }

        //下拉列表内容
        $institutionList = Institution::getInstitutionSelect($institution);

        $selectDefault['code'] = '0';
        $selectDefault['name'] = "----请选择机构----";
        array_unshift($institutionList, $selectDefault);*/

//        $start = $request->get("page");
//
//        $filter = $request->get("filter");
//        if ($start == '') {
//            $start = 0;
//        } else {
//            $start = ($start - 1) * self::$pageSize;
//        }
//        if ($filter == '') {
//            $filter = 0;
//        }
//
//        $total_page = Institution::getInstitutionContacterListTotal($filter, $institutionId);
        $contacterList = Institution::getInstitutionAllContacterList($institutionCode);
//
//        $pagination = new Pagination([
//            'defaultPageSize' => self::$pageSize,
//            'totalCount' => $total_page,
//        ]);
        return $this->renderPartial('institution-contacter-partial',
            ['institution_code' => $institutionCode,
                'contacter_list' => $contacterList
//                'institutionSelected' => $institutionRecord,
//                'institutionList' => $institutionList,
//                'pagination' => $pagination,
//                'record' => $record,
//                'filter' => $filter
            ]);
    }

//    /**
//     * 联系人详情
//     * @return string
//     */
//    public function actionInstitutionContacterDetailHandler()
//    {
//        $request = \Yii::$app->request;
//        $userId = $request->post("id");
//        $record = Institution::getInstitutionContacter($userId);
//        return $this->renderJson(['record' => $record], 0, 0);
//    }

    /**
     * 确认添加修改机构联系人
     * @return string
     */
    public function actionAddContacterHandler()
    {
        $request = \Yii::$app->request;
        $record = [];
        $record['code'] = $request->post("institutionCode");
        $record['id'] = $request->post("id");
        $record['name'] = $request->post("name");
        $record['phone'] = $request->post("phone");
        $record['email'] = $request->post("email");
        $record['remark'] = $request->post("remark");
        $record['isDelete'] = 0;

        $id = Institution::manageInstitutionContacter($record);

        if ($id == null) {
            return $this->renderJson(null, 100, '操作错误!');
        } else {
            return $this->renderJson($id);
        }
    }

    /**
     * 确认添加修改机构联系人
     * @return string
     */
    public function actionDelContacterHandler()
    {
        $request = \Yii::$app->request;
        $record = [];
        $record['code'] = '';
        $record['id'] = $request->post("id");
        $record['name'] = '';
        $record['phone'] = '';
        $record['email'] = '';
        $record['remark'] = '';
        $record['isDelete'] = 1;
        $id = Institution::manageInstitutionContacter($record);

        if ($id == null) {
            return $this->renderJson(null, 100, '操作错误!');
        } else {
            return $this->renderJson($id);
        }
    }

    /**
     * 获取指定机构下的下级机构（用于上级机构更新数据到下级机构所用）
     * str : institution_code 机构编号
     * int : type 操作的数据类别（1--机构商品池 2--商品分类 3--扩展分类 4--特价活动 5--广告设置 6--广告分类）
     * institution-childlist-part-view
     */
    public function actionInstitutionChildlistPartView()
    {

        $request = Yii::$app->request;
        $institution_code = $request->post("institution_code");
        $type = $request->post("type");
        $childlist = InstitutionUpdateRecord::getUnderInstitutions($institution_code, $type);
        return $this->renderPartial('institution-childlist-part-view', ['list' => $childlist]);
    }

    /**
     * 同步下级机构数据
     * @return string
     */
    public function actionSysUnderInstitutionData()
    {
        $request = \Yii::$app->request;
        $super_institution_code = $request->post('super_institution_code');
        $institution_code_list = $request->post('institution_code_list');
        //type  1--机构商品池 2--商品分类 3--扩展分类 4--特价活动 5--广告设置 6--广告分类
        $type = $request->post('type');
        $status = 0;
        $message = '';
        switch ($type) {
            case 1:
                Goods::sysUnderInstitutionGoods($super_institution_code, $institution_code_list);
                break;
            case 2:
                Goods::sysUnderInstitutionGoodsCategory($super_institution_code, $institution_code_list);
                break;
            case 3:
                Goods::sysUnderInstitutionGoodsExtendCategory($super_institution_code, $institution_code_list);
                break;
            case 4:
                if (!Activity::sysUnderInstitutionBargain($super_institution_code, $institution_code_list)) {
                    $status = 1;
                    $message = '同步出现错误';
                }
                break;
            case 5:
                if (!Information::sysUnderInstitutionAd($super_institution_code, $institution_code_list)) {
                    $status = 1;
                    $message = '同步出现错误，请检查是否先同步广告分类';
                }
                break;
            case 6:
                if (!Information::sysUnderInstitutionAdCategory($super_institution_code, $institution_code_list)) {
                    $status = 1;
                    $message = '同步出现错误';
                }
                break;

        }


        return $this->renderJson(null, $status, $message);
    }


    /**
     * 部门设置
     * @return string
     */
    public function actionDepartmentList()
    {
        //--获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构--------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //----------------------------------------------------------------------------

        $request = \Yii::$app->request;
        $page = $request->get('page', 1);//分页起始页默认为1
        $name = $request->get('name');


        $institution_code = $institution;
        if ($institution_code == '0') {
            $institution_code = $request->get("institution_code", '');
        }

        //下拉列表相关数据
        $institutions = Institution::getInstitutionSelectList($institution, $institution_code)['institutionList'];

        /*$institution_code = $request->get('institution_code');

        if($institution_code==''){
            $institution_code=$institution;
        }
        $currentManager = Manager::getCurrentManager();
        $institutions = null;
        if (Permission::isSystemAdmin()) {
            $institutions = Institution::getAllEnabledListWithHierarchy($currentManager['institution_code']);
        } else {
            $institutions = Institution::getAllEnabledSelfChildren($currentManager['institution_code']);
        }*/
        $roleList = Role::getAllEnabledList();

        //取得产品总数 -用于分页
        $DataCount = 0;
        $PageSize = 100;
        $DataCount = Department::getCount($institution_code, $name);
        $list = Department::getList($page, $PageSize, $institution_code, $name);

        $pagination = new Pagination([
            'defaultPageSize' => $PageSize,
            'totalCount' => $DataCount,
        ]);
        return $this->render('department-list', [
            'pagination' => $pagination,
            'list' => $list,
            'name' => $name,
            'institutions' => $institutions,
            'institution_code' => $institution_code,
            'roleList' => $roleList
        ]);
    }

    /**
     * 部门编辑
     * @return string
     */
    public function actionDepartmentPartView()
    {
        $this->layout = false;

        $request = \Yii::$app->request;
        $id = $request->post('id');
        $item = Department::getDepartment($id);
        if ($item != null) {
            $parent_item = Department::getDepartment($item['parent_id']);
            $item['parent_code'] = '';
            if ($parent_item != null) {
                $item['parent_code'] = $parent_item['code'];
            }
        }

        $institution_code = Manager::getCurrentManager()['institution_code'];
        $departments = Department::getListTree($institution_code);

        return $this->render('department-part-view',
            [
                'item' => $item,
                'departments' => $departments
            ]);
    }

    /**
     * 获取部门树形结构数据
     * @return string
     */
    public function actionDepartmentTreeHandler()
    {
        $manager = Manager::getCurrentManager();
        $institution_code = \Yii::$app->request->post('institution_code', $manager['institution_code']);
        $manager_id = $manager['id'];

        $departments = null;
        if (Department::isDepartmentManager($manager_id)) {
            $departments = Department::getListTree2($institution_code, $manager_id);
        } else {
            $departments = Department::getListTree($institution_code);
        }

        return $this->renderJson($departments, 0, '');
    }

    /**
     * 部门编辑提交
     * @return string
     */
    public function actionDepartmentSaveHandler()
    {
        $request = \Yii::$app->request;
        $institution_code = $request->post('institution_code');
        $id = $request->post('id');
        $name = $request->post('name');
        $remark = $request->post('remark');
        $parent_id = $request->post('parent_id', '');

        $result = Department::saveDepartment($id, $name, $remark, $parent_id, $institution_code);
        if ($result) {
            return $this->renderJson(null, 0, '执行成功');
        }
        return $this->renderJson(null, 1, '执行失败');
    }

    /**
     * 删除部门
     * @return string
     */
    public function actionDepartmentDelHandler()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $result = Department::delDepartment($id);
        if (!$result) {
            return $this->renderJson(null, 1, '操作错误!');
        }
        return $this->renderJson(null, 0, '操作成功!');
    }

    /**
     * 添加部门用户view
     * @return string
     */
    public function actionDepartmentPartAdduserView()
    {
        $this->layout = false;

        $request = \Yii::$app->request;
        $department_id = $request->post('id');
        $institution_code = $request->post('institution_code');
        $items = User::getUserNotInDepartment($department_id, $institution_code);
        return $this->render('department-part-user-view', [
            'items' => $items,
            'department_id' => $department_id
        ]);
    }

    /**
     * 删除部门用户view
     * @return string
     */
    public function actionDepartmentPartDeluserView()
    {
        $this->layout = false;

        $request = \Yii::$app->request;
        $department_id = $request->post('id');
        $institution_code = $request->post('institution_code');
        $items = User::getUserInDepartment($department_id, $institution_code);
        return $this->render('department-part-user-view', [
            'items' => $items,
            'department_id' => $department_id
        ]);
    }

    /**
     * 添加部门用户Handler
     * @return string
     */
    public function actionDepartmentAdduserHandler()
    {
        $request = \Yii::$app->request;
        $department_id = $request->post('department_id');
        $user_array = $request->post('user_array');
        $result = Department::addUsersToDepartment($department_id, $user_array);
        if (!$result) {
            return $this->renderJson(null, 1, '操作失败!');
        }
        return $this->renderJson(null, 0, '操作成功!');
    }

    /**
     * 添加部门用户Handler
     * @return string
     */
    public function actionDepartmentDeluserHandler()
    {
        $request = \Yii::$app->request;
        $department_id = $request->post('department_id');
        $user_array = $request->post('user_array');
        $result = Department::delUserFromDepartment($department_id, $user_array);
        if (!$result) {
            return $this->renderJson(null, 1, '操作失败!');
        }
        return $this->renderJson(null, 0, '操作成功!');
    }

    /**
     * 导出机构列表
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function actionExportInstitutionListHandler()
    {
        //--获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构--------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //----------------------------------------------------------------------------
        $request = \Yii::$app->request;


        $status = $request->post("status");
        $filter = $request->post("filter");
        $filterP = $request->post("filterP");
        $insList = Institution::getInstitutionList(0, 0, $status, $filter, $filterP, $institution);
        $objPHPExcel = \PHPExcel_IOFactory::load(self::$demo_file);
        // 给表格添加数据

        //得到当前活动的表,注意下文教程中会经常用到$objActSheet
        //$objActSheet = $objPHPExcel->getActiveSheet();
        $i = 2;
        foreach ($insList as $item) {

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $item['code']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, $item['name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $item['address']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $item['create_datetime']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, $item['contacter']);

            $i++;

        }
        // 给当前活动的表设置名称
        //$objActSheet->setTitle('Simple2222');
        if (\Yii::$app->params['iswindows']) {
            //windows下使用该
            $filename = self::$download . '\subinstitution' . time() . '.xlsx';
        } else {
            //Linux下使用
            $filename = self::$download . '//' . 'subinstitution' . time() . '.xlsx';
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($filename);

        return $this->renderJson($filename, 0, 0);
    }
}